package cn.springcloud.fix.provider.controller;

import cn.springcloud.fix.common.core.base.R;
import cn.springcloud.fix.common.log.annotation.AsyncLog;
import cn.springcloud.fix.provider.dao.mapper.NovelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ProviderController {

    @Autowired
    private DiscoveryClient client;

    @Autowired
    private NovelMapper novelMapper;

    @AsyncLog(value = "discovery")
    @GetMapping("/discovery")
    public Object discovery() {
        List<String> list = client.getServices();
        System.out.println("**********" + list);
        List<ServiceInstance> srvList = client.getInstances("SPRINGCLOUD-PROVIDER");
        for (ServiceInstance element : srvList) {
            System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t" + element.getUri());
        }
        return this.client;
    }

    @AsyncLog(value = "getHeaders")
    @GetMapping("/getHeaders")
    public R<Object> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        Enumeration<String> headNames = request.getHeaderNames();
        while (headNames.hasMoreElements()) {
            String headName = headNames.nextElement();
            map.put(headName, request.getHeader(headName));
            System.out.println(headName + ":" + request.getHeader(headName));
        }
        return R.SUCCESS(map);
    }

    @AsyncLog(value = "testQuery")
    @GetMapping("/testQuery")
    public Object testQuery() {
        return novelMapper.selectList(null);
    }
}
